package biz

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"io"
	"net/http"
)

type MapService struct {
	log *log.Helper
}

func NewMapServiceBiz(logger log.Logger) *MapService {
	return &MapService{
		log: log.NewHelper(logger),
	}
}
func (msbiz *MapService) GetDriverInfo(origin, destination string) (string, string, error) {
	key := "973759af4832eb1dd9a560c10da2e7f9"
	api := "https://restapi.amap.com/v3/direction/driving"
	parameters := fmt.Sprintf("origin=%s&destination=%s&extensions=base&output=JSON&key=%s", origin, destination, key)
	url := api + "?" + parameters
	resp, err := http.Get(url)
	if err != nil {
		return "", "", err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", "", err
	}
	//解析出来
	ddr := &DirectionDrivingResp{}
	if err := json.Unmarshal(body, ddr); err != nil {
		return "", "", err
	}
	//判断lsb请求结果
	if ddr.Status == "0" {
		return "", "", errors.New(ddr.Info)
	}

	//fmt.Println(string(body))
	path := ddr.Route.Paths[0]
	return path.Distance, path.Duration, nil
}

type DirectionDrivingResp struct {
	Status   string `json:"status,omitempty"`
	Info     string `json:"info,omitempty"`
	Infocode string `json:"infocode,omitempty"`
	Route    struct {
		Origin      string  `json:"origin,omitempty"`
		Destination string  `json:"destination,omitempty"`
		Paths       []Paths `json:"paths,omitempty"`
	} `json:"route,omitempty"`
}

type Paths struct {
	Distance string `json:"distance,omitempty"`
	Duration string `json:"duration,omitempty"`
	Strategy string `json:"strategy,omitempty"`
}
